package xutils

import (
	"errors"
	"net"
	"strings"
)

var (
	ERR_NO_LOCAL_IP_FOUND = errors.New("没有找到网卡IP")
)

// 获取本机网卡IP
func GetLocalIP() (ipv4 string, err error) {
	// 获取所有网卡
	addrs, err := net.InterfaceAddrs()
	if err != nil {
		return "", err
	}
	// 获取第一个非lo的网卡IP
	for _, addr := range addrs {
		// 这个网络地址是IP地址 ipv4 ipv6
		if ipNet, isIpNet := addr.(*net.IPNet); isIpNet && !ipNet.IP.IsLoopback() {
			// 跳过IPV6
			if ipNet.IP.To4() != nil {
				ipv4 = ipNet.IP.String() // 192.168.1.1
				return
			}
		}
	}

	err = ERR_NO_LOCAL_IP_FOUND
	return
}

func GetOutBoundIP() (ip string, err error) {
	conn, err := net.Dial("udp", "8.8.8.8:53")
	if err != nil {
		return
	}
	localAddr := conn.LocalAddr().(*net.UDPAddr)
	ip = strings.Split(localAddr.String(), ":")[0]
	return
}
